package com.zeeephr.core.sax;

import java.util.ArrayList;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.zeeephr.core.bean.Clz;
import com.zeeephr.core.bean.ClzMapper;


public class WebHandler extends DefaultHandler {
	private ArrayList<Clz> clzs;
	private ArrayList<ClzMapper> clzMappers;
	boolean isMapper;
	String tag;
	public void startDocument() throws SAXException {
		clzs=new ArrayList<>();
		clzMappers=new ArrayList<>();
		isMapper=false;
		tag="";
	}

	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		tag=qName;
		if("servlet".equals(qName)) {
			isMapper=false;
			clzs.add(new Clz());
		}
		else if("servlet-mapping".equals(qName)){
			isMapper=true;
			clzMappers.add(new ClzMapper());
		}
		
	}

	public void characters(char[] ch, int start, int length) throws SAXException {
		String value=new String(ch,start,length).trim();
		if(value.length()>0) {
			if(isMapper) {
				if("servlet-name".equals(tag)) {
					clzMappers.get(clzMappers.size()-1).setName(value);
				}
				if("url-pattern".equals(tag)) {
					clzMappers.get(clzMappers.size()-1).getUrl().add(value);
				}
			}
			else {
				if("servlet-name".equals(tag))clzs.get(clzs.size()-1).setName(value);
				if("servlet-class".equals(tag))clzs.get(clzs.size()-1).setWhere(value);
			}
		}
		
		
	}

	
	@Override
	public void endDocument() throws SAXException {

		for(Clz c:clzs) System.out.println(c);
		for(ClzMapper m:clzMappers)System.out.println(m);
	}

	public ArrayList<Clz> getClzs() {
		return clzs;
	}

	public ArrayList<ClzMapper> getClzMappers() {
		return clzMappers;
	}
	
}
